package xyz.xxpc.springcloud.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;

public class HttpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(10086);
        boolean serverShutdown = false;
        while (!serverShutdown) {
            // 拿到和客户端的一个连接
            Socket client = serverSocket.accept();
            System.out.println("一个客户端上来了");

            // 获取到输入流的读取器
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(client.getInputStream())
            );
            boolean process = true;

            while (true) {
                String line = in.readLine(); // 读取一行请求头信息
                if(line == null){
                    // 没有请求头 直接关闭连接
                    process = false;
                    break;
                }
                System.out.println(line);
                break;
//                if (line == null || line.length() == 0) {
//
//                }
            }
            if(process) {
                // 输出内容到客户端
                PrintWriter out = new PrintWriter(client.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append("hello client!" + System.currentTimeMillis() + "<br>\n");
                int code = 200;
                try {
                    sb.append("current user count:" + DbTool.userCount());
                } catch (Exception e) {
                    code = 500;
                    sb.append(e.getMessage());
                    e.printStackTrace();
                }
                // 输出头
                out.println("HTTP/1.1 " + code);
                out.println("Content-Type: text/html;charset=utf-8");
                out.println();
                System.out.println(sb);
                // 输出内容
                out.println(sb.toString());
                out.flush();
                out.close();
            }
            // 关闭所有的资源
            in.close();

            client.close();


        }
        //ERR_INVALID_HTTP_RESPONSE
    }
}
